﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Windows.Forms;
using TracyGUI.UIComponent;
using Tracy;
using SharedLib.Helpers;

namespace TracyGUI
{
    public partial class FormMain
    {
        private const string FILE_SETTINGS_LAYOUT = "Layout.xml";
        private void LoadLayout()
        {
            if (File.Exists(FILE_SETTINGS_LAYOUT))
            {
                XmlDocument doc = new XmlDocument();
                try
                {
                    doc.Load(FILE_SETTINGS_LAYOUT);
                    LoadLayout(doc.SelectSingleNode("/layout") as XmlElement);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Failed to load layout settings: " + ex.Message);
                }
            }

            if (_tabControlContent.TabPages.Count == 0)
            {
                _tabControlContent.TabPages.Add(CreateEntryTab(TabPageEntry.TABPAGE_NAME_ALL));
            }
        }

        public void LoadLayout(XmlElement rootNode)
        {
            if (rootNode != null)
            {
                LoadEntryTabLayout(rootNode.SelectSingleNode("entry-tabs") as XmlElement);
                LoadDownloadManagerSettings(rootNode.SelectSingleNode("download-manager") as XmlElement);
                LoadUESelection(rootNode.SelectSingleNode("ultra-explorer") as XmlElement);
            }
        }

        private void LoadUESelection(XmlElement node)
        {
            if (node != null)
            {
                //Classifier set combobox selection
                string classifierSet = node.GetAttribute("classifier-set");
                if (!String.IsNullOrEmpty(classifierSet))
                {
                    if (comboBoxUE.Items.Contains(classifierSet))
                    {
                        comboBoxUE.SelectedItem = classifierSet;
                    }
                }

                XmlNodeList classiferNodes = node.SelectNodes("classifier");
                if (classiferNodes.Count > 0)
                {
                    TreeNode parentNode = _ueEntry.TreeView.Nodes[0];
                    if (classiferNodes.Count == 1) //Select "All Entries"
                    {
                        _ueEntry.TreeView.SelectedNode = parentNode;
                        SelectUENode(parentNode);
                    }
                    else //Select other node
                    {

                        for (int i = 1; i < classiferNodes.Count; i++)
                        {
                            string key = classiferNodes[i].InnerText;
                            foreach (TreeNode subNode in parentNode.Nodes)//expand treeview
                            {
                                if (subNode.Name == key)
                                {
                                    subNode.Nodes.Clear();
                                    _ueEntry.GenerateFilterChildNodes(subNode);
                                    if (i < classiferNodes.Count - 1)
                                    {
                                        subNode.Expand();
                                        parentNode = subNode;
                                    }
                                    else
                                    {
                                        _ueEntry.TreeView.SelectedNode = subNode;
                                        SelectUENode(subNode);
                                    }
                                    
                                }
                            }
                        }
                    }
                }
            }
        }

        private void LoadDownloadManagerSettings(XmlElement node)
        {
            if (node != null)
            {
                if (XmlHelper.GetNodeValue(node, "auto-download") == "on")
                {
                    IsAutoDownloadMode = true;
                }
                else
                {
                    IsAutoDownloadMode = false;
                }
            }
        }

        private void LoadEntryTabLayout(XmlElement entryTabControlNode)
        {
            if (entryTabControlNode != null)
            {
                //Load entry tabs
                foreach (XmlElement tabNode in entryTabControlNode.SelectNodes("tab"))
                {
                    TabPageEntry tab;
                    string tabName = tabNode.GetAttribute("name");
                    if (tabName == TabPageEntry.TABPAGE_NAME_UE) continue;//TODO: save&load layout for ultraexplorer
                    string searchKeyword = tabNode.GetAttribute("search");
                    TracyFacade.Instance.SearchEngine.Search(searchKeyword);

                    tab = CreateEntryTab(tabName, searchKeyword);
                    if (tab == null) continue;
                    _tabControlContent.TabPages.Add(tab);
                    if (tabNode.GetAttribute("selected") == "true") _tabControlContent.SelectedTab = tab;
                    if (tabNode.GetAttribute("default") == "true") _selectedEntryPage = tab; //Default tab for selected entry
                    if (!String.IsNullOrEmpty(searchKeyword)) _searchEntryPage = tab;

                    //Load sub tabs
                    foreach (XmlElement subTabNode in tabNode.SelectNodes("sub-tab"))
                    {
                        string subTabName = subTabNode.GetAttribute("name");
                        if (tab.TabControl.TabPages.ContainsKey(subTabName))
                        {
                            TabPage subTab = tab.TabControl.TabPages[subTabName];
                            if (subTabNode.GetAttribute("selected") == "true")
                            {
                                tab.TabControl.SelectedTab = subTab;
                            }

                            XmlElement listViewNode = subTabNode.SelectSingleNode("list-view") as XmlElement;
                            if (listViewNode != null)
                            {
                                //Load list view settings
                                EnhancedListView listView = null;
                                if (subTab is TabPageFiles)
                                {
                                    listView = ((TabPageFiles)subTab).ListViewItems;
                                }
                                else if (subTab is TabPageResources)
                                {
                                    listView = ((TabPageResources)subTab).ListViewItems;
                                }
                                if (listView != null)
                                {
                                    listView.SetSortColumn(Convert.ToInt32(listViewNode.GetAttribute("sort-column")), listViewNode.GetAttribute("sort-order"));
                                    listView.Sort();
                                }
                            }
                        }
                    }

                }
            }
        }

        private void SaveLayout()
        {
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(SaveLayout(doc));
            try
            {
                doc.Save(FILE_SETTINGS_LAYOUT);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        public XmlElement SaveLayout(XmlDocument doc)
        {
            XmlElement rootNode = doc.CreateElement("layout");
            SaveEntryTabLayout(doc, rootNode);
            SaveDownloadManagerSettings(doc, rootNode);
            SaveUESelection(doc, rootNode);
            return rootNode;
        }

        private void SaveUESelection(XmlDocument doc, XmlElement rootNode)
        {
            XmlElement node = rootNode.AppendChild(doc.CreateElement("ultra-explorer")) as XmlElement;
            if (comboBoxUE.SelectedIndex != -1)
            {
                node.SetAttribute("classifier-set", comboBoxUE.SelectedItem.ToString());
                XmlNode classifierNode = null;
                if (_selectedUETreeNode != null)
                {
                    TreeNode tn = _selectedUETreeNode;
                    do{
                        
                        if (classifierNode != null)
                        {
                            classifierNode = node.InsertBefore(doc.CreateElement("classifier"), classifierNode);
                        }else{
                            classifierNode = node.AppendChild(doc.CreateElement("classifier"));
                        }

                        classifierNode.InnerText = tn.Name;
                        tn = tn.Parent;
                    }while(tn != null);
                }
            }
        }

        private void SaveDownloadManagerSettings(XmlDocument doc, XmlElement rootNode)
        {
            XmlElement node = rootNode.AppendChild(doc.CreateElement("download-manager")) as XmlElement;
            node.AppendChild(XmlHelper.CreateElementWithTextValue("auto-download", IsAutoDownloadMode?"on":"off",doc));
        }

        private void SaveEntryTabLayout(XmlDocument doc, XmlElement rootNode)
        {
            XmlElement tabsNode = rootNode.AppendChild(doc.CreateElement("entry-tabs")) as XmlElement;
            foreach (TabPageEntry tab in _tabControlContent.TabPages)
            {
                //Save entry tab
                XmlElement tabNode = doc.CreateElement("tab");
                tabNode.SetAttribute("name", tab.Name);
                if (tab == _tabControlContent.SelectedTab) tabNode.SetAttribute("selected", "true");
                if (tab == _selectedEntryPage) tabNode.SetAttribute("default", "true");
                if (tab == _searchEntryPage)
                {
                    tabNode.SetAttribute("search", tab.Tag.ToString());
                }

                foreach (TabPage subTab in tab.TabControl.TabPages)
                {
                    //Save sub tab
                    XmlElement subTabNode = doc.CreateElement("sub-tab");
                    subTabNode.SetAttribute("name", subTab.Name);
                    if (subTab == tab.TabControl.SelectedTab) subTabNode.SetAttribute("selected", "true");

                    //Save list view settings
                    EnhancedListView listView = null;
                    if (subTab is TabPageFiles)
                    {
                        listView = ((TabPageFiles)subTab).ListViewItems;
                    }
                    else if (subTab is TabPageResources)
                    {
                        listView = ((TabPageResources)subTab).ListViewItems;
                    }
                    if (listView != null)
                    {
                        ListViewColumnSorter sorter = listView.ListViewItemSorter as ListViewColumnSorter;
                        if (sorter != null && sorter.Order != SortOrder.None)
                        {
                            XmlElement listViewNode = doc.CreateElement("list-view");
                            listViewNode.SetAttribute("sort-column", sorter.SortColumn.ToString());
                            listViewNode.SetAttribute("sort-order", (sorter.Order == SortOrder.Ascending) ? "asc" : "desc");
                            subTabNode.AppendChild(listViewNode);
                        }
                    }

                    tabNode.AppendChild(subTabNode);
                }
                tabsNode.AppendChild(tabNode);
            }
        }
    }
}
